package com.openlab.service.notice.controller;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.openlab.common.dto.UserTokenDto;
import com.openlab.common.utils.Result;
import com.openlab.common.utils.ResultCode;
import com.openlab.common.utils.TokenManager;
import com.openlab.service.notice.dto.*;
import com.openlab.service.notice.entity.NoticeToUser;
import com.openlab.service.notice.entity.NoticeTpl;
import com.openlab.service.notice.service.NoticeToUserService;
import com.openlab.service.notice.service.NoticeTplService;

import com.openlab.service.notice.vo.NoticeInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author admin
 * 小区通知控制器
 */
@RestController
@RequestMapping("/notice")
@CrossOrigin
public class NoticeController {

    @Autowired
    private NoticeToUserService noticeToUserService;
    @Autowired
    private NoticeTplService noticeTplService;

    @GetMapping("/tpl")
    public Result tpl(){
        return Result.ok();
    }

    /**
     * 分页查询并在页面显示数据
     * @param noticeParam
     * @return
     */
    @PostMapping("/list")
    public Result list(@RequestBody NoticeParam noticeParam){


        IPage<NoticeInfoDto> page = noticeToUserService.selectPage(noticeParam);

        List<NoticeInfoVo> list=new ArrayList<>();
        page.getRecords().forEach(noticeInfoDto -> {
            NoticeInfoVo build = NoticeInfoVo.builder()
                    .id(noticeInfoDto.getId())
                    .title(noticeInfoDto.getTitle())
                    .notice_tpl_id(ObjectUtils.isEmpty(noticeInfoDto.getNoticeTplId()) ? noticeInfoDto.getNoticeTplId(): null)
                    .published(noticeInfoDto.getPublished())
                    .published_at(noticeInfoDto.getPublishedAt())
                    .created_at(noticeInfoDto.getCreatedAt())
                    .created_by(noticeInfoDto.getCreatedBy())
                    .real_name(noticeInfoDto.getRealName())
                    .build();
            list.add(build);
        });
        HashMap<String, Object> data = new HashMap<>();
        data.put("list",list);
        data.put("total",page.getTotal());
        data.put("page_amount",page.getPages());
        data.put("page_num",noticeParam.getPage_num());
        data.put("page_size",noticeParam.getPage_size());
        return Result.ok(200,data);
    }

    /**
     * 创建发布消息的数据
     * @param noticeCreateParam 前端请求返回的参数
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/create")
    public Result create(@RequestBody Map<String,Object> noticeCreateParam, HttpServletRequest httpServletRequest) {


        UserTokenDto userTokenDto = TokenManager.getNameByJwtToken(httpServletRequest);
        String userTokenDtoId = String.valueOf(userTokenDto.getId());


        String title = (String) noticeCreateParam.get("title");
        String overview = (String) noticeCreateParam.get("overview");
        Integer published = (Integer) noticeCreateParam.get("published");
        String tpl = (String) noticeCreateParam.get("tpl");
        boolean oa_tpl_msg = (boolean) noticeCreateParam.get("oa_tpl_msg");
        Integer community_id = (Integer) noticeCreateParam.get("community_id");
        String content = JSON.toJSONString(noticeCreateParam.get("content"));

        NoticeTpl noticeTpl = null;
        if (!oa_tpl_msg) {
             noticeTpl = NoticeTpl.builder()
                    .tpl(tpl)
                    .content(content)
                    .build();
            noticeTplService.save(noticeTpl);
        }

        NoticeToUser noticeToUser = NoticeToUser.builder()
                .title(title)
                .overview(overview)
                .communityId(community_id.longValue())
                .content(content)
                .published(published)
                .publishedAt(!ObjectUtils.isEmpty(published) ? new Date().getTime() : 0)
                .publishedBy(!ObjectUtils.isEmpty(published) ? Long.parseLong(userTokenDtoId) : 0)
                .noticeTplId(noticeTpl == null ? null : noticeTpl.getId())
                .createdAt(new Date().getTime())
                .createdBy(Long.valueOf(userTokenDtoId))
                .build();

        noticeToUserService.save(noticeToUser);
        /*
         * 创建返回给前端的对象
         */
        Map<String, Object> data = new HashMap<>();

        data.put("id",noticeToUser.getId());

        System.out.println(noticeToUser.getId());
        return Result.ok(200,data);
    }

    /**
     * 用户查看显示发布通知页面数据
     * @param idParam 前端请求返回的参数
     * @return 返回展示成功
     */
    @PostMapping("/detail")
    public Result detail(@RequestBody IdParam idParam){

        Map<String, Object> detail = noticeToUserService.detail(idParam.getId(), idParam.getCommunity_id());

        if (ObjectUtils.isEmpty(detail)){
            return Result.error(ResultCode.QUERY_ILLEFAL,"不存在的通知");
        }
        String tpl_title = "非法模板";

        String published_real_name = null;

        if(!ObjectUtils.isEmpty(detail.get("published_by"))){
            published_real_name = String.valueOf(detail.get("published_by"));
        }

        String content = (String) detail.get("content");
        String s = content.replaceAll("\"", "'");
        detail.put("content", s);
        detail.put("tpl_title",tpl_title);
        detail.put("published_real_name",published_real_name);

        return Result.ok(200,detail);
    }

    /**
     * 发布小区通知
     * @param idParam
     * @param request
     * @return
     */
    @PostMapping("/published")
    public Result published(@RequestBody IdParam idParam, HttpServletRequest request){
        QueryWrapper<NoticeToUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", idParam.getId());
        queryWrapper.eq("community_id",idParam.getCommunity_id());

        NoticeToUser detail = noticeToUserService.getOne(queryWrapper);

        if (ObjectUtils.isEmpty(detail)){
            return Result.error(ResultCode.QUERY_ILLEFAL,"非法的小区通知");
        }

        if (ObjectUtils.isEmpty(detail.getPublished())){
            return Result.ok(ResultCode.STATUS_ERROR,"通知已发布");
        }
        /**
         * 获取用户id
         */
        UserTokenDto token = TokenManager.getNameByJwtToken(request);
        Integer userId = Integer.valueOf(token.getId());

        UpdateWrapper<NoticeToUser> queryWrapper1 = new UpdateWrapper<>();
        queryWrapper1.set("published",detail.getPublished() == 0 ? 1:detail.getPublished());
        queryWrapper1.set("published_by", userId);
        queryWrapper1.set("published_at", new Date().getTime());
        queryWrapper1.eq("id",detail.getId());
        queryWrapper1.eq("community_id",detail.getCommunityId());
        boolean update = noticeToUserService.update(queryWrapper1);

        if (!update){
            return Result.error(ResultCode.DATA_MODEL_UPDATE_FAIL,"发布通知失败");
        }

        HashMap<String, Object> data = new HashMap<>();
        data.put("published_at",new Date().getTime());
        return Result.ok(200,data);
    }

    /**
     * 更新小区通知
     * @param updateParam
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Map<String,Object> updateParam){


        String content = JSON.toJSONString(updateParam.get("content"));


        QueryWrapper<NoticeToUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",updateParam.get("id"));
        queryWrapper.eq("community_id",updateParam.get("community_id"));

        NoticeToUser detail = noticeToUserService.getOne(queryWrapper);

        if (ObjectUtils.isEmpty(detail)){
            return Result.error(ResultCode.QUERY_ILLEFAL,"非法的小区通知");
        }
        if (detail.getPublished() == 1){
            return Result.error(ResultCode.STATUS_ERROR,"已发布的通知不能更新");
        }
        Long noticeTplId = detail.getNoticeTplId();
        if (!ObjectUtils.isEmpty(updateParam.get("oa_tpl_msg"))){
            if (!ObjectUtils.isEmpty(noticeTplId)){
                UpdateWrapper<NoticeTpl> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id",detail.getNoticeTplId());
                updateWrapper.set("tpl",updateParam.get("tpl"));
                updateWrapper.set("content",content);

                noticeTplService.update(updateWrapper);
            }
            else {
                noticeTplService.save(NoticeTpl.builder()
                                .tpl((String) updateParam.get("tpl"))
                                .content(String.valueOf(content))
                                .build());
            }
        }else {
            if (ObjectUtils.isEmpty(noticeTplId)){
                noticeTplService.removeById(detail.getNoticeTplId());
                noticeTplId  = null;
            }
        }
        UpdateWrapper<NoticeToUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", detail.getId());
        updateWrapper.eq("community_id", detail.getCommunityId());
        updateWrapper.set("title", updateParam.get("title"));
        updateWrapper.set("overview", updateParam.get("overview"));
        updateWrapper.set("content", content);
        updateWrapper.set("published", detail.getPublished());
        updateWrapper.set("published_at", ObjectUtils.isEmpty(detail.getPublished()) ? new Date().getTime():null);
        updateWrapper.set("notice_tpl_id", detail.getNoticeTplId());

        boolean update = noticeToUserService.update(updateWrapper);

        if (!update){
            return Result.error(ResultCode.DATA_MODEL_UPDATE_FAIL,"修改小区通知失败");
        }

        return Result.ok(200,"修改小区通知成功");
    }
}
